#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include "mrj_supt.h"
#include "mpx_supt.h"
#include "R3.H"

//void load_cmd(char*);
void load_process(char*, int);
//void terminate_cmd(char*);
//int strint(char*);

void load_process(char* prgm_name, int priority){
	pcb* fresh;
	int APP_CLASS = 1;
	int error_code;
	int prgm_size;
	int start_offset_p;
	context* cp;
	unsigned char* load_address;
	unsigned char* execution_address;
	char* prgm_dir = "\0";  //current directory
	
	

	error_code = sys_check_program(prgm_dir, prgm_name, &prgm_size, &start_offset_p);
	//printf("sys_check_progam error_code: %d\n", error_code);
		load_address = (unsigned char*) sys_alloc_mem(prgm_size*sizeof(unsigned char));
	
	
	execution_address = load_address + start_offset_p;
	fresh = setPCB(prgm_name, priority, APP_CLASS);

	if((error_code == 0) && fresh){
		fresh->susp = PCB_FLAG_SUSP;
		fresh->state = PCB_STATE_RDY;
		fresh->locAddr = load_address;
		fresh->excAddr = execution_address;
		fresh->memSize = prgm_size;
		enqueueReady(fresh);
	}else{
		printf("Load process error. Click monkey sticks for more details.\n");
	}
	error_code = sys_load_program(load_address, PCB_STACK_SIZE, prgm_dir, prgm_name);
	//printf("sys_load_program error_code: %d\n", error_code);
	
	cp = (context *) fresh->stackT;
		
	cp->IP = FP_OFF(execution_address);
	cp->CS = FP_SEG(execution_address);
	cp->FLAGS = 0x200;
	cp->DS = _DS;
	cp->ES = _ES;
}

/*void load_cmd(char* arg_line){
	char** args = parse_cmd(arg_line);
	int priority = 0;
	int i;
	if(searchPCBbyName(args[0])==0){
		if(args[1]==NULL){
			load_process(args[0], 0);
		}else{
			printf("parsed priority= %d\n", strint(args[1]));
			load_process(args[0], strint(args[1]));
		}
	}
	else{
		printf("Load fail. Process already exists.\n");
	}
}


//assuming pcb->Pclass 0 is system process
void terminate_cmd(char* pName){
	pcb* pbj = searchPCBbyName(pName);
	if(pbj!=0){
		if(pbj->Pclass == 1){
			free_pcb(pbj);
		}else{
			printf("Could not terminate process %s. It is a system process.\n", pName);
		}
	}else{
		printf("Could not terminate process %s. Does Not Exist.\n", pName);
	}
}
*/
int free_pcb(pcb *freebird){
	int error_code;
	error_code = sys_free_mem(freebird->locAddr);
	//printf("free_pcb load address error_code: %d\n", error_code);
	error_code = sys_free_mem(freebird);
	//printf("free_pcb pcb error_code: %d\n", error_code);
	return error_code;
}